import {
  Form,
  Input,
  Image,
  Rate,
  Select,
  InputNumber,
  Button,
  Radio,
  message,
  Spin,
  ColorPicker,
  Modal,
} from "antd";
import { namespace } from "../configFile";
import { getItem } from "@/utils/localstorage";
import { TOKEN } from "@/constants";
import { useEffect, useState } from "react";
import { DeleteOutlined } from "@ant-design/icons";
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import { Editor, Toolbar } from "@wangeditor/editor-for-react";
import { connect, history } from "umi";
import styles from "../styles.less";
import { useParams } from "react-router-dom";
import UploadPreview from "@/components/UploadPreview/index"; //上传图片预览组件
import Https from "@/utils/Https";
import { PageContainer } from "@ant-design/pro-components";
const ItemBox = (props) => {
  const { dispatch, info, isFooter } = props;
  const [editor, setEditor] = useState(null);
  const [baseInfoForm] = Form.useForm();
  const [courseUrlList, setCourseUrlList] = useState([
    "https://oss.zkwcloud.com/imgs/imgs/public/course-default.png",
  ]);
  const [defaultSort, setdefaultSort] = useState(-1);
  const params = useParams();
  const [loading, setLoading] = useState(false);
  // 编辑器内容
  const [html, setHtml] = useState("");
  const [modal, contextHolder] = Modal.useModal();
  let editorConfig = {
    MENU_CONF: {},
    placeholder: "请输入内容",
  };
  editorConfig.MENU_CONF["uploadImage"] = {
    server: "/spark-frontend/system/user/uploadPic",
    fieldName: "file",
    headers: {
      clientid: "e5cd7e4891bf95d1d19206ce24a7b32e",
      Authorization: getItem(TOKEN),
    },
    customInsert(res, insertFn) {
      insertFn(res.data);
    },
  };

  useEffect(() => {
    dispatch({
      type: `${namespace}/getCategoryList`,
    });
    dispatch({
      type: `${namespace}/getVenueList`,
    });
  }, []);

  const onVenueChange = (item) => {
    baseInfoForm.setFieldsValue({ courseCoachInfo: "" });
    dispatch({
      type: `${namespace}/getCoachList`,
      params: {
        venueId: item.value,
      },
    });
  };
  //课程默认时间
  const courseList = [15, 30, 45, 60, 75, 90, 105, 120, 135,150,165,180,195,210,225,240,255,270,285,300];
  const submit = () => {
    baseInfoForm.validateFields().then(async (request) => {
      request.courseSort =
        defaultSort === 0
          ? 0
          : request.courseSubSort > 0
          ? request.courseSubSort
          : 100;
      request.courseCoverUrl =
        courseUrlList.length > 0 ? courseUrlList.toString() : "";
      request.courseCategoryName = request.courseCategoryName.toString();
      request.courseIntroduce = html == "<p><br></p>" ? "" : html;
      // request.venueId = request.venueInfo.value;
      // request.venueName = request.venueInfo.label;
      request.courseCoachId = request.courseCoachInfo.value;
      request.courseCoachName = request.courseCoachInfo.label;
      request.teachingMode = 1;
      request.classHourCost = request.classHourCost
        ? (Number(request.classHourCost) * 100).toFixed(2)
        : 0;
      const { courseSubSort, ...otherParams } = request;
      if (params.num) {
        let obj = {
          id: params.id,
          ...otherParams,
        };
        let res: any = await Https.post("/course/updateCourseInfo", obj, true);
        setLoading(true);
        if (res.code === 200) {
          message.success("保存成功");
          history.push("/course/info", { courseType: params.courseType });
        } else {
          message.error(res.msg);
        }
        setLoading(false);
      } else {
        props.submit(0, otherParams);
      }
    });
  };
  //保存草稿
  const saveDraft = async () => {
    let request = baseInfoForm.getFieldsValue();
    request.courseSort =
      defaultSort === 0
        ? 0
        : request.courseSubSort > 0
        ? request.courseSubSort
        : 100;
    request.courseCoverUrl =
      courseUrlList.length > 0 ? courseUrlList.toString() : "";
    request.courseCategoryName = request.courseCategoryName
      ? request.courseCategoryName.toString()
      : "";
    request.courseIntroduce = html == "<p><br></p>" ? "" : html;
    //request.venueId = request.venueInfo ? request.venueInfo.value : "";
    //request.venueName = request.venueInfo ? request.venueInfo.label : "";
    request.courseCoachId = request.courseCoachInfo
      ? request.courseCoachInfo.value
      : "";
    request.courseCoachName = request.courseCoachInfo
      ? request.courseCoachInfo.label
      : "";
    request.teachingMode = 1;
    request.classHourCost = request.classHourCost
      ? (Number(request.classHourCost) * 100).toFixed(2)
      : 0;
    const { courseSubSort, ...otherParams } = request;
    let obj = {
      ...otherParams,
      courseType: params.courseType,
      courseStatus: 2,
      id: params.id ? params.id : null,
    };
    let url = params.id ? "/course/updateInfo" : "/course/addInfo";
    let res: any = await Https.post(url, obj, true);
    setLoading(true);
    if (res.code === 200) {
      message.success("保存成功");
      history.push("/course/info", { courseType: params.courseType });
    } else {
      message.error(res.msg);
    }
    setLoading(false);
  };
  //取消创建课程
  const cancel = () => {
    modal.confirm({
      title: "提示",
      icon: null,
      content: `是否取消${params.id ? "编辑" : "创建"}课程信息?`,
      okText: "确认",
      cancelText: "取消",
      onOk: () => {
        history.push("/course/info", { courseType: params.courseType });
      },
    });
  };
  useEffect(() => {
    if (Object.keys(info).length > 0) {
      baseInfoForm.setFieldsValue({
        courseName: info.courseName,
        courseCategoryName: info.courseCategoryIds,
        // venueInfo: info.venueId
        //   ? {
        //       value: info.venueId,
        //       label: info.venueName,
        //     }
        //   : null,
        courseCoachInfo: info.courseCoachId
          ? {
              value: info.courseCoachId,
              label: info.courseCoachName,
            }
          : null,
        classHourCost: info.classHourCost
          ? (Number(info.classHourCost) / 100).toFixed(2)
          : 0,
        courseDuration: info.courseDuration,
        courseDifficulty: info.courseDifficulty,
        peopleNumMax: info.peopleNumMax,
        openClassPeopleNum: info.openClassPeopleNum,
        allowJoinClassFlag: Number(info.allowJoinClassFlag),
        courseSort: info.courseSort == 0 ? 0 : -1,
        courseSubSort: info.courseSort == 0 ? 100 : info.courseSort,
        courseCoverUrl: info.courseCoverUrl
          ? info.courseCoverUrl.split(",")
          : null,
        colour: info.colour,
      });
      setCourseUrlList(
        info.courseCoverUrl ? info.courseCoverUrl.split(",") : []
      );
      setHtml(info.courseIntroduce);
      setdefaultSort(info.courseSort == 0 ? 0 : -1);
    }
    dispatch({
      type: `${namespace}/getCoachList`,
      params: {
        venueId: getItem("venueInfo").id,
      },
    });
  }, [info]);
  return (
    <Spin spinning={loading}>
      <PageContainer
        footer={[
          isFooter ? (
            <div className={styles.formBtn} style={{ zIndex: 9999 }}>
              {params.num ? (
                <Button type="primary" size="large" onClick={() => submit()}>
                  保存
                </Button>
              ) : (
                <>
                  <Button type="default" size="large" onClick={() => cancel()}>
                    取消
                  </Button>
                  {(!params.id || info.courseStatus == "2") && (
                    <Button
                      style={{ marginLeft: "15px" }}
                      type="default"
                      size="large"
                      onClick={() => saveDraft()}
                    >
                      保留草稿
                    </Button>
                  )}
                  <Button
                    style={{ marginLeft: "15px" }}
                    type="primary"
                    size="large"
                    onClick={() => submit()}
                  >
                    下一步
                  </Button>
                </>
              )}
            </div>
          ) : null,
        ]}
      >
        <Form
          form={baseInfoForm}
          className={styles.BaseInfoForm}
          layout="vertical"
          initialValues={{
            courseSort: -1,
            allowJoinClassFlag: 0,
            courseDifficulty: 3,
            courseSubSort: 100,
            peopleNumMax: 1,
            colour: "#1677FF",
            courseDuration: 60,
            courseCoverUrl:
              "https://oss.zkwcloud.com/imgs/imgs/public/course-default.png",
          }}
        >
          <Form.Item
            label="课程名称"
            name="courseName"
            rules={[{ required: true, message: "请输入课程名称" }]}
          >
            <Input
              maxLength={30}
              placeholder="请输入课程名称，限30个字"
              showCount
              allowClear
            />
          </Form.Item>
          <Form.Item
            label="课程分类"
            name="courseCategoryName"
            rules={[{ required: true, message: "请选择课程分类" }]}
          >
            <Select
              mode="multiple"
              style={{ width: "100%" }}
              placeholder="请选择课程分类"
              allowClear
              options={props.categoryList}
              fieldNames={{
                label: "categoryName",
                value: "id",
              }}
            />
          </Form.Item>
          {/* <Form.Item
            label="所属场馆"
            name="venueInfo"
            rules={[{ required: true, message: "请选择所属场馆" }]}
          >
            <Select
              labelInValue
              style={{ width: "100%" }}
              placeholder="请选择所属场馆"
              onChange={onVenueChange}
              options={props.venueList}
              fieldNames={{
                label: "venueName",
                value: "id",
              }}
            />
          </Form.Item> */}
          <Form.Item
            label="授课老师"
            name="courseCoachInfo"
            //tooltip={"先选择具体的场馆，再选择该场馆下的授课老师！"}
            rules={[{ required: true, message: "请选择授课老师" }]}
          >
            <Select
              labelInValue
              style={{ width: "100%" }}
              placeholder="请选择授课老师"
              options={props.coachList}
              fieldNames={{
                label: "nickName",
                value: "userId",
              }}
            />
          </Form.Item>
          {params.courseType == "1" && (
            <Form.Item label="课时费(元/节)" name="classHourCost">
              <InputNumber
                style={{ width: "100%" }}
                controls={false}
                min={0}
                precision={2}
                placeholder="请输入"
              />
            </Form.Item>
          )}
          <Form.Item
            label="单节课时长（分钟）"
            name="courseDuration"
            rules={[{ required: true, message: "请选择单节课时长。" }]}
          >
            <Select placeholder="请选择单节课时长">
              {courseList &&
                courseList.map((item) => (
                  <Select.Option key={item} value={item}>
                    {item}
                  </Select.Option>
                ))}
            </Select>
          </Form.Item>
          {params.courseType != "1" && (
            <Form.Item
              label="可约人数"
              name="peopleNumMax"
              rules={[{ required: true, message: "请输入最多可预约人数" }]}
            >
              <InputNumber
                style={{ width: "100%" }}
                min={1}
                max={1000}
                precision={0}
                controls={false}
                suffix="人"
                placeholder="请输入最多可预约人数"
              />
            </Form.Item>
          )}
          {params.courseType != "1" && (
            <Form.Item
              label="颜色"
              name="colour"
              rules={[{ required: true, message: "请选择颜色" }]}
            >
              <ColorPicker
                showText
                disabledAlpha
                onChange={(e) => {
                  baseInfoForm.setFieldsValue({ colour: e.toHexString() });
                }}
              />
            </Form.Item>
          )}
          <Form.Item label="课程难度" name="courseDifficulty">
            <Rate />
          </Form.Item>
          {params.courseType == "3" ? (
            <>
              <Form.Item
                label="开班人数"
                name="openClassPeopleNum"
                rules={[{ required: true, message: "请输入人数上限" }]}
              >
                <InputNumber
                  style={{ width: "100%" }}
                  controls={false}
                  min={0}
                  precision={0}
                  placeholder="请输入"
                />
              </Form.Item>
              <Form.Item
                label="是否允许插班"
                name="allowJoinClassFlag"
                rules={[{ required: true, message: "请输入人数上限" }]}
              >
                <Radio.Group>
                  <Radio value={1}>是</Radio>
                  <Radio value={0}>否</Radio>
                </Radio.Group>
              </Form.Item>
            </>
          ) : null}
          <Form.Item
            label="课程排序"
            tooltip={"课程在会员端展示的顺序，自定义值越大越靠前！"}
            rules={[{ required: true, message: "请选择课程序号" }]}
          >
            <div className={styles.course_box}>
              <Form.Item noStyle name="courseSort">
                <Radio.Group
                  style={{
                    width: "230px",
                  }}
                  onChange={(e) => {
                    let { value } = e.target;
                    setdefaultSort(value);
                  }}
                >
                  <Radio value={0}>置顶</Radio>
                  <Radio value={-1}>自定义</Radio>
                </Radio.Group>
              </Form.Item>
              {defaultSort == -1 && (
                <Form.Item
                  noStyle
                  name="courseSubSort"
                  style={{
                    flex: 1,
                    margin: "0 8px",
                  }}
                >
                  <InputNumber
                    placeholder="请输入排序值,输入的值越大，展示越靠前"
                    min={1}
                    max={10000}
                    defaultValue={1}
                    precision={0}
                    controls={false}
                    style={{ width: "100%" }}
                  />
                </Form.Item>
              )}
            </div>
          </Form.Item>
          {params.courseType != "3" && (
            <Form.Item
              label="课程封面"
              name="courseCoverUrl"
              extra="图片格式支持：.png .jpg，尺寸推荐比例：16:9，最多可上传3张图"
              rules={[{ required: true, message: "请选择课程封面" }]}
              style={{ width: "100%" }}
            >
              <div className={styles.upload_box}>
                {courseUrlList.length > 0 && (
                  <div className={styles.avatar_box}>
                    {courseUrlList.map((item, index) => (
                      <div className={styles.avatar_item} key={index}>
                        <Image width={160} height={90} src={item} />
                        <a
                          onClick={() => {
                            let objList = [...courseUrlList];
                            objList.splice(index, 1);
                            baseInfoForm.setFieldsValue({
                              courseCoverUrl: objList,
                            });
                            setCourseUrlList(objList);
                          }}
                        >
                          <DeleteOutlined
                            style={{ fontSize: "15px", color: "#ffffff" }}
                          />
                        </a>
                      </div>
                    ))}
                  </div>
                )}
                {courseUrlList.length < 3 && (
                  <UploadPreview
                    aspect={16 / 9}
                    onSuccess={(e) => {
                      let objList = [...courseUrlList];
                      objList.push(e);
                      baseInfoForm.setFieldsValue({ courseCoverUrl: objList });
                      setCourseUrlList(objList);
                    }}
                  />
                )}
              </div>
            </Form.Item>
          )}
          <Form.Item
            label="课程介绍"
            name="courseIntroduce"
            extra="图片格式支持：.png .jpg，尺寸推荐比例：16:9"
            style={{ width: "100%", marginRight: 0 }}
          >
            <div id="courseIntroduce">
              <Toolbar
                editor={editor}
                defaultConfig={{
                  excludeKeys: ["insertVideo", "uploadVideo", "emotion"],
                }}
                mode="default"
                style={{ borderBottom: "1px solid #ccc" }}
              />
              <Editor
                defaultConfig={editorConfig}
                value={html}
                onCreated={setEditor}
                onChange={(editor) => {
                  setHtml(editor.getHtml());
                }}
                mode="default"
                style={{ height: "310px", overflowY: "auto" }}
              />
            </div>
          </Form.Item>
        </Form>
      </PageContainer>
      {contextHolder}
    </Spin>
  );
};
export default connect((state) => {
  return {
    ...state[namespace],
    submitLoading: state.loading.effects[`${namespace}/submitItem`],
  };
})(ItemBox);
